package com.aierkeji.b2c.service;

import java.io.File;
import java.io.IOException;
import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import com.aierkeji.b2c.dao.BaseJPADao;
import com.aierkeji.b2c.dao.jpa.AkjFileDao;
import com.aierkeji.b2c.entity.AkjFile;
import com.aierkeji.b2c.utils.AppConfig;
import com.aierkeji.b2c.utils.DateTimeUtils;
import com.aierkeji.b2c.utils.FileUtils;

@Service
public class AkjFileService extends BaseService<AkjFile,String> {

    @Autowired
    AkjFileDao akjFileDao;

    @Override
    public BaseJPADao<AkjFile, String> getBaseDao() {
        return akjFileDao;
    }

    @Transactional
    public AkjFile uploadFile(MultipartFile multiFile, String mark) throws IOException {

        String originalName = multiFile.getOriginalFilename().replaceAll(" ", "");

        String extension = FileUtils.getExtension(originalName);


        String path = "/" + mark + "/"
                    + DateTimeUtils.converDateToString(new Date(), DateTimeUtils.DATE_PATTERN_DAY_01) + "/";
        File folder = new File(AppConfig.getProperty("user_data_path") + path);
        if (!folder.exists()) {
            folder.mkdirs();
        }
        String savePath = AppConfig.getProperty("user_data_path") + path + originalName;// 图片终极路径
        File file = new File(savePath);

        FileUtils.writeToFile(multiFile.getInputStream(), file);

        AkjFile uFile = new AkjFile();
        uFile.setCreateTime(DateTimeUtils.getCurrentTime());
        uFile.setFileName(originalName);
        uFile.setFileType(extension);
        uFile.setMark(mark);
        uFile.setOriginName(originalName);
        uFile.setPath(path);
        akjFileDao.save(uFile);
        return uFile;
    }

}
